1850H - The Third Letter - CodeForces Solution


dfs and similar graphs greedy implementation

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll powi(ll a, ll b)
{
    if (b == 0)
        return 1;
    if (b % 2 == 0)
    {
        ll k = powi(a, b / 2);
        return k * k;
    }
    else
    {
        ll k = powi(a, b / 2);
        return a * k * k;
    }
}

ll maxl(ll a, ll b)
{
    if (a > b)
    {
        return a;
    }
    return b;
}

ll minl(ll a, ll b)
{
    if (a < b)
    {
        return a;
    }
    return b;
}
void dfs(vector<pair<ll, ll>> adj[],vector<ll>&vis,vector<ll>&dis,int i,ll dip){
    vis[i]=1;
    dis[i]=dip;
    for(auto it:adj[i]){
        int node=it.first;
        int tmdis=it.second;
        if (vis[node]==0)
        {
            dfs(adj,vis,dis,node,dip+tmdis);
        }
        else if (dis[node]!=dip+tmdis )
        {
            dis[node]=LLONG_MAX;
        }
    }
}
int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int n, m;
        cin >> n >> m;
        int a, b, d;
        vector<pair<ll, ll>> adj[n + 1];
        for (int i = 0; i < m; i++)
        {
            cin >> a >> b >> d;

            adj[a].push_back({b, d});

            adj[b].push_back({a, -1*d});
        }
        vector<ll>vis(n+1,0);
        vector<ll>dis(n+1,LLONG_MIN);
        for (int i = 1; i < n+1 ; i++)
        {
            if (vis[i]==0)
            {
                dfs(adj,vis,dis,i,0);
            }
            
        }
        // for (auto it:dis)
        // {
        //     cout<<it<<" ";
        // }cout<<endl;
        int chk=0;
        for (auto it:dis)
        {
            if (it==LLONG_MAX )
            {
                chk=1;
                break;
            }
            
        }
        if (chk )
        {
            cout<<"NO"<<endl;
        }
        else{
            cout<<"YES"<<endl;
        }
        
        
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

1093A - Dice Rolling
1360B - Honest Coach
1399C - Boats Competition
1609C - Complex Market Analysis
1657E - Star MST
1143B - Nirvana
1285A - Mezo Playing Zoma
919B - Perfect Number
894A - QAQ
1551A - Polycarp and Coins
313A - Ilya and Bank Account
1469A - Regular Bracket Sequence
919C - Seat Arrangements
1634A - Reverse and Concatenate
1619C - Wrong Addition
1437A - Marketing Scheme
1473B - String LCM
1374A - Required Remainder
1265E - Beautiful Mirrors
1296A - Array with Odd Sum
1385A - Three Pairwise Maximums
911A - Nearest Minimums
102B - Sum of Digits
707A - Brain's Photos
1331B - Limericks
305B - Continued Fractions
1165B - Polycarp Training
1646C - Factorials and Powers of Two
596A - Wilbur and Swimming Pool
1462B - Last Year's Substring